package com.sz.mes.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.exception.BusinessException;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.D;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Status;

import com.diboot.file.controller.BaseExcelFileController;
import com.diboot.file.excel.BaseExcelModel;
import com.diboot.file.excel.listener.ReadExcelListener;
import com.diboot.file.util.ExcelHelper;

import com.sz.mes.entity.ProductTask;
import com.sz.mes.entity.PurchaseOrder;
import com.sz.mes.dto.PurchaseOrderDTO;
import com.sz.mes.entity.RequestPurchase;
import com.sz.mes.excel.model.ProductTaskImportModel;
import com.sz.mes.excel.model.RequestPurchaseImportModel;
import com.sz.mes.mapper.PurchaseOrderMapper;
import com.sz.mes.mapper.RequestPurchaseMapper;
import com.sz.mes.service.PurchaseOrderService;
import com.sz.mes.vo.PurchaseOrderListVO;
import com.sz.mes.excel.listener.PurchaseOrderImportListener;
import com.sz.mes.excel.model.PurchaseOrderImportModel;
import com.sz.mes.excel.model.PurchaseOrderExportModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 采购订单 Excel处理Controller
 *
 * @author hem
 * @version 1.0
 * @date 2024-01-10
 * Copyright © szhs
 */
@RestController
@RequestMapping("/purchaseOrder/excel")
@BindPermission(name = "采购订单导入导出", code = "PurchaseOrderExcel")
@Slf4j
public class PurchaseOrderExcelController extends BaseExcelFileController {

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    /**
     * 预览数据
     *
     * @param file
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "导入预览", code = OperationCons.CODE_IMPORT)
    @PostMapping("/preview")
    public JsonResult preview(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
//        purchaseOrderMapper.deleteAll();
//        purchaseOrderMapper.truncateAll();
        return super.excelPreview(file, PurchaseOrder.class, params);
    }

    /**
     * 导入预览保存
     *
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "导入预览保存", code = OperationCons.CODE_IMPORT)
    @PostMapping("/previewSave")
    public JsonResult previewSave(@RequestParam Map<String, Object> params) throws Exception {
//        purchaseOrderMapper.deleteAll();
        purchaseOrderMapper.truncateAll();
        return super.excelPreviewSave(params);
    }

    /**
     * 上传excel并保存
     *
     * @param file
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "直接导入", code = OperationCons.CODE_IMPORT)
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
//        purchaseOrderMapper.deleteAll();
        purchaseOrderMapper.truncateAll();
        return super.uploadExcelFile(file, PurchaseOrder.class, params);
    }

    @Override
    protected <T extends BaseExcelModel> void readExcelFile(InputStream inputStream, String fileExt, ReadExcelListener<T> listener) throws Exception {
        try {
            //ExcelHelper.read(inputStream, "csv".equalsIgnoreCase(fileExt) ? ExcelTypeEnum.CSV : null, listener, listener.getExcelModelClass());
            EasyExcel.read(inputStream,listener.getExcelModelClass(),listener).headRowNumber(2).excelType("csv".equalsIgnoreCase(fileExt) ? ExcelTypeEnum.CSV : null).sheet().doRead();
        } catch (Exception var5) {
            log.warn("解析excel文件失败", var5);
            if (var5 instanceof BusinessException) {
                throw var5;
            } else if (V.notEmpty(var5.getMessage())) {
                throw new Exception(var5.getMessage());
            } else {
                throw var5;
            }
        }
    }

    /**
     * 下载示例文件
     *
     * @param response
     * @throws Exception
     */
    @BindPermission(name = "导入采购订单示例文件下载", code = OperationCons.CODE_IMPORT)
    @GetMapping("/downloadExample")
    public void downloadExample(HttpServletResponse response) throws Exception {
        String fileName = "采购订单导入示例.xlsx";
        ExcelHelper.exportExcel(response, fileName, PurchaseOrderImportModel.class, null);
    }

    /**
     * 采购订单列表导出
     *
     * @param response
     * @return
     * @throws Exception
     */
    @BindPermission(name = "导出列表文件", code = OperationCons.CODE_EXPORT)
    @GetMapping("/export")
    public JsonResult export(PurchaseOrderDTO purchaseOrderDto, @RequestParam(value = "columns", required = false) List<String> columns,
                             HttpServletResponse response) throws Exception {
        QueryWrapper<PurchaseOrder> queryWrapper = super.buildQueryWrapperByQueryParams(purchaseOrderDto);
        List<PurchaseOrderListVO> purchaseOrderList = purchaseOrderService.getViewObjectList(queryWrapper, null, PurchaseOrderListVO.class);
        if (V.isEmpty(purchaseOrderList)) {
            return new JsonResult(Status.FAIL_OPERATION, "采购订单列表为空，导出失败");
        }
        String fileName = "采购订单列表导出_" + D.today() + ".xlsx";
        List<PurchaseOrderExportModel> dataList = this.entityList2ExcelList(purchaseOrderList);
        ExcelHelper.exportExcel(response, fileName, PurchaseOrderExportModel.class, columns, dataList);
        return null;
    }

    /**
     * 实体列表转excel列表
     *
     * @param purchaseOrderList
     * @return
     */
    private List<PurchaseOrderExportModel> entityList2ExcelList(List<PurchaseOrderListVO> purchaseOrderList) {
        if (V.isEmpty(purchaseOrderList)) {
            return Collections.emptyList();
        }
        return BeanUtils.convertList(purchaseOrderList, PurchaseOrderExportModel.class);
    }

    @Override
    protected ReadExcelListener<PurchaseOrderImportModel> getExcelDataListener() {
        return new PurchaseOrderImportListener();
    }

    /**
     * 上传excel并保存
     *
     * @param file
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "重复数据执行更新", code = OperationCons.CODE_IMPORT)
    @PostMapping("/update")
    public JsonResult update(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {

        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        threadPool.submit(() -> {
            ArrayList<PurchaseOrderImportModel> purchaseOrderImportModels = new ArrayList<>();
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                EasyExcel.read(inputStream, PurchaseOrderImportModel.class, new AnalysisEventListener<PurchaseOrderImportModel>() {
                    @Override
                    public void invoke(PurchaseOrderImportModel reportExcel, AnalysisContext analysisContext) {
                        // 将读取到的每一行存入reportDetails集合中
                        purchaseOrderImportModels.add(reportExcel);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    }
                }).sheet().doRead();
            } catch (IOException e) {
                e.printStackTrace();
            }
            List<PurchaseOrder> purchaseOrderList = purchaseOrderMapper.selectList(null);
            if (purchaseOrderList.size() > 0) {
                try {
                    List<PurchaseOrderImportModel> purchaseOrderImportModelList = BeanUtils.convertList(purchaseOrderList, PurchaseOrderImportModel.class);
                    List<PurchaseOrderImportModel> result = purchaseOrderImportModelList.stream()
                            .filter(a -> !purchaseOrderImportModelList.contains(a))
                            .collect(Collectors.toList());
                    //后续在此处进行业务处理
                    if (result.size() > 0) {
                        for (PurchaseOrderImportModel purchaseOrderImportModel : result) {
                            QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
                            wrapper.eq("receipt_num", purchaseOrderImportModel.getReceiptNum());
                            wrapper.eq("row_num", purchaseOrderImportModel.getRowNum());
                            PurchaseOrder purchaseOrderDB = purchaseOrderMapper.selectOne(wrapper);
                            PurchaseOrder purchaseOrder = BeanUtils.convert(purchaseOrderImportModel, PurchaseOrder.class);
                            if (purchaseOrderDB != null) {
                                Long id = purchaseOrderDB.getId();
                                purchaseOrder.setId(id);
                                purchaseOrderMapper.updateById(purchaseOrder);
                            } else {
                                purchaseOrderMapper.insert(purchaseOrder);
                            }

                        }
                    }

                } finally {
                    threadPool.shutdown();
                }
            }
        });
        return JsonResult.OK();
    }

}
